package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.CUR_DATE;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: 售后管理
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class AfterSaleRunnable implements Exe {


    private Connection connection;

    private static final String ALL_CLIENT_SQL = "select * from  jcClientInformation";

    private List<String> firstList = Arrays.asList(
            "请协助核查生产批次并反馈根本原因分析报告",
            "经初步判断属于工艺瑕疵，请车间质量部在24小时内处理",
            "请对照质检标准确认是否属于出厂前漏检情况",
            "退货品已返回工厂仓库，请车间48小时内完成处理",
            "明确发货产品质量问题，请马上核查问题原因尽快处理"
    );

    private List<String> secondList = Arrays.asList(
            "问题已经处理，已经发货给客户",
            "次品已经按要求都维修好",
            "设备参数有误，已经调整处理客户问题",
            "货品已装车出库，预计今天到客户工厂",
            "规格生产错误，已经返工重新加工"
    );


    public AfterSaleRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        //销售订单
        List<Integer> saleOrderIds = GEN_ORDER_IDS.get();

        if (CollectionUtil.isEmpty(saleOrderIds))
            return Boolean.FALSE;


        try {
            Map<Integer, LinkedHashMap<String, Object>> clientMap = DbUtil.resultSetToList(connection.prepareStatement(ALL_CLIENT_SQL).executeQuery())
                    .stream().collect(Collectors.toMap(cur -> (int) cur.get("id"), cur -> cur));

            List<LinkedHashMap<String, Object>> saleOrders = DbUtil.resultSetToList(connection.prepareStatement("select  * from salesOrders").executeQuery())
                    .stream().filter(cur -> saleOrderIds.contains(((int) cur.get("id")))).toList();

            int num = 0;
            int afterSaleId = getMaxId(connection, "aftersalesWork");
            int postSaleDetailId = getMaxId(connection, "postsaleList");
            int detailsOfPostsaleWorkOrdersId = getMaxId(connection, "detailsOfPostsaleWorkOrders");
            for (LinkedHashMap<String, Object> saleOrder : saleOrders) {
                //百分之10的几率生成售后
                if (RandomUtil.randomInt(100) > 30) continue;
                num++;
                PreparedStatement statement = connection.prepareStatement("insert into aftersalesWork(id,postsaleWorkOrderNumber,associatedSalesOrders,client,otherOrganiser,contactCall,dateOfFeedback,typeOfProblem,processStatus,remarks)values (?,?,?,?,?,?,?,?,?,?)");
                statement.setInt(1, ++afterSaleId);
                statement.setString(2,GenUtil.getNoFromTable(connection, "SH", "aftersalesWork", "postsaleWorkOrderNumber"));
                statement.setInt(3, (int) saleOrder.get("id"));
                int clientId = (int) saleOrder.get("clientInformation");
                statement.setInt(4, clientId);
                LinkedHashMap<String, Object> client = clientMap.get(clientId);
                statement.setString(5, (client.get("otherOrganiser1").toString()));
                statement.setString(6, ObjectUtil.isNotNull(client.get("contactDetails"))?client.get("contactDetails").toString():"/");
                statement.setDate(7, Date.valueOf(CUR_DATE.get()));
                statement.setString(8, RandomUtil.randomEle(Arrays.asList("质量问题","工艺问题","其他问题")));
                statement.setString(9, "已完结");
                statement.setString(10, "加急处理");
                statement.execute();

                //查询销售订单详情
                statement = connection.prepareStatement("select * from xs02SalesOrderBreakdown where associatedSalesOrders=?");
                statement.setInt(1, (int) saleOrder.get("id"));
                List<LinkedHashMap<String, Object>> maps = DbUtil.resultSetToList(statement.executeQuery());
                for (LinkedHashMap<String, Object> map : maps) {
                    statement = connection.prepareStatement("insert into postsaleList(id,f8ca,productInformation,numberAfterSale,quantityOfShipments)values (?,?,?,?,?)");
                    statement.setInt(1, ++postSaleDetailId);
                    statement.setInt(2, afterSaleId);
                    statement.setInt(3, (int) map.get("productInformation"));
                    BigDecimal quantity = (BigDecimal) map.get("quantityOfShipments");
                    statement.setBigDecimal(5, quantity);
                    statement.setBigDecimal(4, RandomUtil.randomBigDecimal(BigDecimal.ZERO, quantity.add(BigDecimal.ONE)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    statement.execute();
                }

                //服务明细1
                statement = connection.prepareStatement("insert into detailsOfPostsaleWorkOrders(id,otherOrganiser1,otherOrganiser2,positions,associatedPostsaleWorksheets,communicationDescription,time)values (?,?,?,?,?,?,?)");
                statement.setInt(1, ++detailsOfPostsaleWorkOrdersId);
                statement.setString(2, (client.get("otherOrganiser1").toString()));
                statement.setString(3,ObjectUtil.isNotNull(client.get("contactDetails"))?client.get("contactDetails").toString():"/");
                statement.setString(4, "");
                statement.setInt(5, afterSaleId);
                statement.setString(6, RandomUtil.randomEle(firstList));
                long dayOfMs = new SimpleDateFormat("yyyy-MM-dd").parse(CUR_DATE.get().toString()).getTime();
                Timestamp firstTime = new Timestamp(RandomUtil.randomLong(dayOfMs+9*60*60*1000,dayOfMs+17*60*60*1000));
                statement.setTimestamp(7, firstTime);
                statement.execute();

                //服务明细2
                statement = connection.prepareStatement("insert into detailsOfPostsaleWorkOrders(id,otherOrganiser1,otherOrganiser2,positions,associatedPostsaleWorksheets,communicationDescription,time)values (?,?,?,?,?,?,?)");
                statement.setInt(1, ++detailsOfPostsaleWorkOrdersId);
                statement.setString(2, (client.get("otherOrganiser1").toString()));
                statement.setString(3, ObjectUtil.isNotNull(client.get("contactDetails"))?client.get("contactDetails").toString():"/");
                statement.setString(4, "");
                statement.setInt(5, afterSaleId);
                statement.setString(6, RandomUtil.randomEle(secondList));
                statement.setTimestamp(7, new Timestamp(firstTime.getTime() + RandomUtil.randomInt(2 * 60 * 60 * 1000)));
                statement.execute();
            }

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        return Boolean.TRUE;
    }


}
